﻿﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace VSS_AHT.Data
{
    public class ScaleProcessing
    {
        public delegate bool GetScaleStatusDelegate();
        public GetScaleStatusDelegate GetScaleStatus;

        public delegate void ParseDataDelegate(string weight);
        public ParseDataDelegate ParseData;

        #region Variables

        private string _data = String.Empty;

        #endregion

        #region Methods Port
        public void OpenSerialPort()
        {
            try
            {
                if (!Common.Port.IsOpen) Common.Port.Open();

                Common.Port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(SerialPort_DataReceived);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        public void FreeEventSerialPort()
        {
            try
            {
                Common.Port.DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(SerialPort_DataReceived);
            }
            catch (Exception ex)
            {
                Common.ShowAlert(ex.Message);
            }
        }
        #endregion

        /// <summary>
        /// Data received, receive 1 string / received times
        /// Data Template:
        /// 02 0A 20 47 20 20 20 20 20 20 36 30 20 6B 67 20 0D 0A 41 42 43 44 45 2D 31 32 33 34 5F 5F 61 62 63 64 65 2D

        /// + Transfer method:
        /// Receive: _______ S txxx_______
        /// Trim start: txxx_____
        /// Receive: _________________ E _____________
        /// Concat: txxx_______________________ E ____________
        /// If skip 2 bytes: xx___________________E
        /// Else (get full): txxx___________________E
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void SerialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                bool scaleStatus = false;
                if (GetScaleStatus != null)
                    scaleStatus = GetScaleStatus.Invoke();

                if (scaleStatus)
                {
                    // WriteLog("Start receive data");
                    string dataReceived = Common.Port.ReadExisting();

                    _data = String.Concat(_data, dataReceived);

                    WriteLog("1 : " + _data);

                    // I change for ok all of cases.

                    // Get index of the start byte and the end byte;
                    //byte sByte = 0x47; //G
                    //byte eByte = 0x6B;
                    int startIdx = _data.IndexOf(Convert.ToChar(Common.StartByte));    // index = 0x47;

                    if (startIdx >= 0)
                    {
                        WriteLog("2.Start string: " + _data);

                        _data = _data.Substring(startIdx + 1);
                    }

                    int endIdx = _data.IndexOf(Convert.ToChar(Common.EndByte));
                    // Get String with End Index and Print It.
                    if (endIdx >= 0)
                    {
                        // Process the skip byte and end string.
                        _data = _data.Substring(Common.SkipBytes, endIdx);
                        _data = _data.Trim();

                        WriteLog("3.Complete string: " + _data);

                        // Print it
                        if (ParseData != null)
                            ParseData.Invoke(_data);

                        _data = String.Empty;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Receive data failed. Error details: " + ex.Message);
            }
        }
        //private void ParingData(string data)
        //{
        //    //WriteLog("Result: " + data);

        //    //WriteLog(String.Format("First focused: {0}", this.ActiveControl.Equals(numFirstWeight)));
        //    //WriteLog(String.Format("Second focused: {0}", this.ActiveControl.Equals(numSecondWeight)));


        //        // if (!CurrentPO.HasFirstWeight)
        //        if (FormVehicleScale.nu)
        //        {
        //            //MessageBox.Show("Cân 1: " + data);
        //            this.numFirstWeight.Invoke(new EventHandler(delegate
        //            {
        //                this.numFirstWeight.Value = Int32.Parse(data);
        //            }));
        //        }
        //        // else if (!CurrentPO.HasSecondWeight)
        //        else if (this.ActiveControl.Equals(numSecondWeight))
        //        {
        //            //MessageBox.Show("Cân 2" + data);
        //            this.numSecondWeight.Invoke(new EventHandler(delegate
        //            {
        //                this.numSecondWeight.Value = Int32.Parse(data);
        //            }));
        //        }

        //}



        public void WriteLog(string message)
        {
            if (!File.Exists(Common.logfile))
                File.Create(Common.logfile);
            using (StreamWriter w = File.AppendText(Common.logfile))
            {
                w.WriteLine(String.Format("{0:d} {0:HH:mm} - {1}", DateTime.Now, message));
                // Close the writer and underlying file.
                w.Flush();
                w.Close();
            }
        }
    }
}
